package com.ning.weixin.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import com.ning.weixin.entity.AcQrcode;

/**
 * @author MENG_LI_DONG
 * @version 2018年12月22日 上午1:00:04
 */
@Component
public class AcQrcodeDao {
	private Logger log = LoggerFactory.getLogger(AcQrcodeDao.class);

	@Autowired
	private JdbcTemplate jdbcTemplate;
	public void insert(AcQrcode t){
		final StringBuffer sql = new StringBuffer();
		StringBuffer sqlParams = new StringBuffer();
		final List<Object> params = new ArrayList<>();
		String id = UUID.randomUUID().toString().replaceAll("-", "");
		t.setId(id);
		sql.append("insert into ac_qrcode(id,");
		sqlParams.append("?,");
		params.add(id);
		if(t.getEncrypt()!=null){
			sql.append("encrypt,");
			sqlParams.append("?,");
			params.add(t.getEncrypt());
		}
		if(t.getCreateTime()!=null){
			sql.append("create_time,");
			sqlParams.append("?,");
			params.add(t.getCreateTime());
		}
		
		if(t.getState()!=null){
			sql.append("state,");
			sqlParams.append("?,");
			params.add(t.getState());
		}
		if(t.getLocNo()!=null){
			sql.append("loc_no,");
			sqlParams.append("?,");
			params.add(t.getLocNo());
		}
		if(t.getDeviceNo()!=null){
			sql.append("device_no,");
			sqlParams.append("?,");
			params.add(t.getDeviceNo());
		}
		sql.deleteCharAt(sql.length() - 1);
		sqlParams.deleteCharAt(sqlParams.length() - 1);
		sql.append(") values(").append(sqlParams).append(")");
		log.debug("sql:" + sql);
		try {
			jdbcTemplate.update(sql.toString(), params.toArray());
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}
	}
	
	public AcQrcode get(String id){
		String sql = "select t.* from ac_qrcode t where t.id = ?";
		try {
			return jdbcTemplate.queryForObject(sql, new String[]{id}, new RowMapper<AcQrcode>(){
				@Override
				public AcQrcode mapRow(ResultSet rs, int row)
						throws SQLException {
					AcQrcode t = new AcQrcode();
					Timestamp createTime = rs.getTimestamp("create_time");
					if(createTime!=null){
						t.setCreateTime(new Date(createTime.getTime()));
					}
					t.setDeviceNo(rs.getString("device_no"));
					t.setId(rs.getString("id"));
					t.setLocNo(rs.getString("loc_no"));
					t.setState(rs.getInt("state"));
					return t;
				}
			});
		} catch(Exception e) {
			return null;
		}
	}
}
